package com.lancoo.answer.view.result

import android.graphics.Color
import android.graphics.Typeface
import android.os.Handler
import android.text.Html
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.lancoo.answer.R
import com.lancoo.answer.databinding.EvFragmentResultBinding
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.bean.CognitiveBean
import com.lancoo.answer.model.eventBean.ResultChildClickEvent
import com.lancoo.answer.util.*
import com.lancoo.answer.view.base.BaseVMFragment
//import com.lancoo.answer.view.dialog.DialogLevelUp
import com.lancoo.answer.widget.CountNumberView
import com.lancoo.answer.widget.GifMotorbikesView
import com.lancoo.answer.widget.HtmlTagHandler
import com.xujiaji.happybubble.BubbleLayout
import org.greenrobot.eventbus.EventBus


class ResultFragment : BaseVMFragment<EvFragmentResultBinding>() {

    private var scoreSoundUtils: ScoreSoundUtils? = null
    private var isShowSoundAnim: Boolean = true
    private lateinit var cognitiveBean: CognitiveBean

    companion object {
        private var mIsShowCognition: Boolean = false
        fun loadFragment(isShowCognition: Boolean?): ResultFragment? {
            val resultFragment = ResultFragment()
            mIsShowCognition = isShowCognition!!
            return resultFragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_result
    }


    override fun initView(view: View) {
        //初始化短音频
        scoreSoundUtils = ScoreSoundUtils(requireContext())
        scoreSoundUtils!!.init()
        //获取测试数据
//        val cognitiveBean = GetJsonDataUtil.getCognitiveBeanJson(requireContext())
        cognitiveBean = ConstantBean.cognitiveBean!!
        //todo 加载顶部分数信息
        showResultScoreView(cognitiveBean)
        //todo 加载中部认知分和预估成绩
        if (mIsShowCognition) {
            mBinding.fmResult2.visibility = View.VISIBLE
            showResultCognitiveView(cognitiveBean)
        } else {
            mBinding.fmResult2.visibility = View.GONE
        }
        //todo 加载底部答题卡
        showResultAnswerSheetView(cognitiveBean, true)

    }

    /*
    * 显示成绩view
    * */
    private fun showResultScoreView(cognitiveBean: CognitiveBean) {
        if (requireContext() == null) {
            return
        }
        val mTvMyScoreRate = mBinding.fmResult1.findViewById<TextView>(R.id.TvMyScoreRate)
        val mTvMyScore = mBinding.fmResult1.findViewById<CountNumberView>(R.id.TvMyScore)
        val mTvSlash = mBinding.fmResult1.findViewById<TextView>(R.id.TvSlash)
        val mTvFullScore = mBinding.fmResult1.findViewById<TextView>(R.id.TvFullScore)
        val mLlClassScore = mBinding.fmResult1.findViewById<LinearLayout>(R.id.LlClassScore)
        val mTvClassRank = mBinding.fmResult1.findViewById<TextView>(R.id.TvClassRank)
        val mTvClassAverageScore =
            mBinding.fmResult1.findViewById<TextView>(R.id.TvClassAverageScore)
        val mTvClassHighestScore =
            mBinding.fmResult1.findViewById<TextView>(R.id.TvClassHighestScore)
        val mTvUseTime = mBinding.fmResult1.findViewById<TextView>(R.id.TvUseTime)

        val scoreRate = cognitiveBean.ScoreRate
        val totalStu = cognitiveBean.TotalStu
        val score = cognitiveBean.Score
        val fullScore = cognitiveBean.FullScore
        val rank = cognitiveBean.Rank
        val classAverageScore = cognitiveBean.ClassAverageScore
        val classHighestScore = cognitiveBean.ClassHighestScore
        val duration = cognitiveBean.Duration

        //显示我的得分
        if (scoreRate.isNullOrEmpty()) {
            mTvMyScoreRate.visibility = View.INVISIBLE
        } else {
            mTvMyScoreRate.visibility = View.VISIBLE
            mTvMyScoreRate.text =
                if (scoreRate.contains("%")) "(得分率$scoreRate)" else "(得分率$scoreRate%)"
        }

        if (score == "--" || !isShowSoundAnim) {
            mTvMyScore.text = score
        } else {
            if (score!!.toFloat() > 0) {
                Handler().postDelayed({
                    scoreSoundUtils!!.playSound(0)
                }, 100)
            }
            if (score!!.contains(".")) {
                val length = score!!.substring(score!!.lastIndexOf(".") + 1).length
                if (length == 1) {
                    mTvMyScore.showNumberWithAnimation(
                        score!!.toFloat(),
                        CountNumberView.FLOATREGEX_1
                    );
                } else if (length == 2) {
                    mTvMyScore.showNumberWithAnimation(
                        score!!.toFloat(),
                        CountNumberView.FLOATREGEX_2
                    );
                }
            } else {
                mTvMyScore.showNumberWithAnimation(score!!.toFloat(), CountNumberView.INTREGEX);
            }
        }
        mTvMyScore.typeface =
            Typeface.createFromAsset(requireContext().assets, "fonts/DIN Condensed Bold.ttf")
        mTvSlash.typeface =
            Typeface.createFromAsset(requireContext().assets, "fonts/DIN Condensed Bold.ttf")
        //显示试卷总分
        mTvFullScore.text = fullScore
        mTvFullScore.typeface =
            Typeface.createFromAsset(requireContext().assets, "fonts/DIN Condensed Bold.ttf")
        //显示班级最高分和班级平均得分
        if (classAverageScore.isNullOrEmpty() || classHighestScore.isNullOrEmpty()) {
            mLlClassScore.visibility = View.INVISIBLE
        } else {
            mLlClassScore.visibility = View.VISIBLE
            if (rank.isNullOrEmpty()) {
                mTvClassRank.visibility = View.INVISIBLE
            } else {
                mTvClassRank.visibility = View.VISIBLE
                if (totalStu > 0) {
                    mTvClassRank.text = "班级排名$rank/$totalStu"
                } else {
                    mTvClassRank.text = "班级排名$rank"
                }
            }
            mTvClassAverageScore.text = "班级平均分 $classAverageScore"
            mTvClassHighestScore.text = "班级最高分 $classHighestScore"
        }

        //显示用时
        val hours = TimeUtils.getHours(duration.toLong())
        val mins = TimeUtils.getMins(duration.toLong())
        val secs = TimeUtils.getSeconds(duration.toLong())
        if (duration == 0) {
            mTvUseTime.text = "用时 " + "0'0\""
        } else {
            if (Integer.valueOf(hours) > 0) {
                val text1 = "<myfont color='#ffffff' size='" + DensityUtils.dp2px(
                    requireContext(),
                    20f
                ) + "'>" + hours + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(
                    requireContext(),
                    16f
                ) + "'>" + mins + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(
                    requireContext(),
                    12f
                ) + "'>" + secs + "''" + "</myfont>"
                val spanned1 = Html.fromHtml(text1, null, HtmlTagHandler("myfont"))
                mTvUseTime.text = "用时 $spanned1"
            } else {
                val text1 = "<myfont color='#ffffff' size='" + DensityUtils.dp2px(
                    requireContext(),
                    20f
                ) + "'>" + mins + "'" + "</myfont>" +
                        "<myfont color='#ffffff' size='" + DensityUtils.dp2px(
                    requireContext(),
                    12f
                ) + "'>" + secs + "''" + "</myfont>"
                val spanned1 = Html.fromHtml(text1, null, HtmlTagHandler("myfont"))
                mTvUseTime.text = "用时 $spanned1"
            }
        }
    }

    /*
    * 刷新成绩view
    * */
    fun refreshResultScoreView(mCognitiveBean: CognitiveBean) {
        isShowSoundAnim = false
        cognitiveBean = mCognitiveBean
        showResultScoreView(cognitiveBean)
    }

    /*
    * 显示认知view
    * */
    private fun showResultCognitiveView(cognitiveBean: CognitiveBean) {

        //认知诊断加载动画加载
        Glide.with(this).load(R.raw.ev_loading_cognitive)
            .into(mBinding.fmResult2.findViewById(R.id.IvLoadingCognitive))
        val mLlLoadingCognitive =
            mBinding.fmResult2.findViewById<LinearLayout>(R.id.LlLoadingCognitive)
        val mLlCognitiveView = mBinding.fmResult2.findViewById<LinearLayout>(R.id.LlCognitiveView)
        val mRlGrayCircleBg = mBinding.fmResult2.findViewById<RelativeLayout>(R.id.RlGrayCircleBg)
        val mLlBadgeView = mBinding.fmResult2.findViewById<LinearLayout>(R.id.LlBadgeView)
        val mIvScoreBadge = mBinding.fmResult2.findViewById<ImageView>(R.id.IvScoreBadge)
        val mTvScoreRankName = mBinding.fmResult2.findViewById<TextView>(R.id.TvScoreRankName)
        val mTvScoreRankIndex = mBinding.fmResult2.findViewById<TextView>(R.id.TvScoreRankIndex)
        val mTvCognitiveIndex = mBinding.fmResult2.findViewById<TextView>(R.id.TvCognitiveIndex)
        val mTvEstimateScore = mBinding.fmResult2.findViewById<TextView>(R.id.TvEstimateScore)
        val mViewCognitionProgress1 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewCognitionProgress1)
        val mViewCognitionProgress2 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewCognitionProgress2)
        val mViewCognitionProgress3 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewCognitionProgress3)
        val mViewCognitionProgress4 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewCognitionProgress4)
        val mViewEstimateProgress1 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewEstimateProgress1)
        val mViewEstimateProgress2 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewEstimateProgress2)
        val mViewEstimateProgress3 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewEstimateProgress3)
        val mViewEstimateProgress4 =
            mBinding.fmResult2.findViewById<View>(R.id.ViewEstimateProgress4)
        val mBlChangeCognitive =
            mBinding.fmResult2.findViewById<BubbleLayout>(R.id.BlChangeCognitive)
        val mBlChangeEstimate = mBinding.fmResult2.findViewById<BubbleLayout>(R.id.BlChangeEstimate)
        val mTvChangeCognitive = mBinding.fmResult2.findViewById<TextView>(R.id.TvChangeCognitive)
        val mTvChangeEstimate = mBinding.fmResult2.findViewById<TextView>(R.id.TvChangeEstimate)
        val mRlScaleCognitive =
            mBinding.fmResult2.findViewById<RelativeLayout>(R.id.RlScaleCognitive)
        val mRlScaleEstimate = mBinding.fmResult2.findViewById<RelativeLayout>(R.id.RlScaleEstimate)
        val tvLoadingRemind = mBinding.fmResult2.findViewById<TextView>(R.id.tv_loading_remind)
        val typeFace = Typeface.createFromAsset(requireContext().assets, "happyZCool.ttf")
        tvLoadingRemind.setTypeface(typeFace)
        mLlLoadingCognitive.visibility = View.VISIBLE
        mLlCognitiveView.visibility = View.GONE
        mRlGrayCircleBg.visibility = View.GONE
        mLlBadgeView.visibility = View.GONE

        //加载任务
        val returnFlag = cognitiveBean.CognitionInfo?.ReturnFlag
        if (returnFlag!!) {
            mLlLoadingCognitive.visibility = View.GONE
            mLlCognitiveView.visibility = View.VISIBLE
            mRlGrayCircleBg.visibility = View.VISIBLE
            mLlBadgeView.visibility = View.VISIBLE

            val currCognitiveGradeName = cognitiveBean.CognitionInfo?.CurrCognitiveGradeName
            val lastCognitiveGradeName = cognitiveBean.CognitionInfo?.LastCognitiveGradeName
            val passRate = cognitiveBean.CognitionInfo?.PassRate
            val currCognitiveIndex = cognitiveBean.CognitionInfo?.CurrCognitiveIndex
            val lastCognitiveIndex = cognitiveBean.CognitionInfo?.LastCognitiveIndex
            val currEstimateScore = cognitiveBean.CognitionInfo?.CurrEstimateScore
            val lastEstimateScore = cognitiveBean.CognitionInfo?.LastEstimateScore
            val cognitiveRangeListSize = cognitiveBean.CognitionInfo?.CognitiveRangeList?.size
            val maxCognitiveRange =
                cognitiveBean.CognitionInfo?.CognitiveRangeList!![cognitiveRangeListSize!! - 1]
            val estimateScoreRangeListSize =
                cognitiveBean.CognitionInfo?.EstimateScoreRangeList?.size
            val maxScoreRange =
                cognitiveBean.CognitionInfo?.EstimateScoreRangeList!![estimateScoreRangeListSize!! - 1]


            //显示称号徽章&显示名次
            if (currCognitiveGradeName == "A") {
                mIvScoreBadge.setImageResource(R.mipmap.ev_icon_rank_star_a)
            } else if (currCognitiveGradeName == "B") {
                mIvScoreBadge.setImageResource(R.mipmap.ev_icon_rank_star_b)
            } else if (currCognitiveGradeName == "C") {
                mIvScoreBadge.setImageResource(R.mipmap.ev_icon_rank_star_c)
            } else if (currCognitiveGradeName == "D") {
                mIvScoreBadge.setImageResource(R.mipmap.ev_icon_rank_star_d)
            } else if (currCognitiveGradeName == "E") {
                mIvScoreBadge.setImageResource(R.mipmap.ev_icon_rank_star_e)
            }
            if (passRate == -1f) {
                mTvScoreRankIndex.visibility = View.GONE
            } else {
                mTvScoreRankIndex.visibility = View.VISIBLE
                mTvScoreRankIndex.text = "超越了" + (passRate!! * 100).toInt() + "%的小伙伴"
            }
            LancooAnimUtils.startScaleBigAnim(requireContext(), mLlBadgeView)
            //显示徽章升级动画：若等级提升则显示恭喜弹窗
//            var currLevel = (AsciiUtils.stringToAscii(currCognitiveGradeName).toInt() - 65)
//            var lastLevel = (AsciiUtils.stringToAscii(lastCognitiveGradeName).toInt() - 65)
//            if (currLevel < lastLevel) {
//                Handler().postDelayed({
//                    scoreSoundUtils!!.playSound(1)
//                }, 100)
//                val dialogLevelUp = DialogLevelUp(requireContext(), currLevel)
//                dialogLevelUp.show()
//            }

            //显示认知积分变化&预估成绩变化
            mTvCognitiveIndex.text = DoubleUtils.killlingDouble(
                DoubleUtils.formatDouble(
                    currCognitiveIndex!!.toDouble(),
                    1
                )
            )
            mTvCognitiveIndex.typeface =
                Typeface.createFromAsset(
                    requireContext().assets,
                    "fonts/DIN Condensed Bold.ttf"
                )
            //显示认知积分变化进度及浮标
            var widthA = 0
            Handler().postDelayed({
                widthA = mViewCognitionProgress1.width
                var lastCognitiveIndexWidth =
                    (widthA * lastCognitiveIndex!! / maxCognitiveRange.toInt()).toInt()
                var currentCognitiveIndexWith =
                    (widthA * currCognitiveIndex!! / maxCognitiveRange.toInt()).toInt()

                //显示蓝色进度条
                val params =
                    mViewCognitionProgress2.layoutParams as RelativeLayout.LayoutParams
                if (currCognitiveIndex > lastCognitiveIndex) {
                    val addWidth = currentCognitiveIndexWith - lastCognitiveIndexWidth
                    if (addWidth < 20) {
                        currentCognitiveIndexWith += 20
                    }
                    params.width = currentCognitiveIndexWith
                } else {
                    val addWidth = lastCognitiveIndexWidth - currentCognitiveIndexWith
                    if (addWidth < 20) {
                        lastCognitiveIndexWidth += 20
                    }
                    params.width = lastCognitiveIndexWidth
                }
                mViewCognitionProgress2.layoutParams = params

                if (currCognitiveIndex > lastCognitiveIndex) {
                    //显示绿色增长进度条
                    val params =
                        mViewCognitionProgress3.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = currentCognitiveIndexWith - lastCognitiveIndexWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(lastCognitiveIndexWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewCognitionProgress3.layoutParams = params
                    //显示绿色气泡增长值
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#22d7bb")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))

                    mTvChangeCognitive.text = "+" +
                            DoubleUtils
                                .round(
                                    DoubleUtils
                                        .sub(
                                            currCognitiveIndex.toDouble(),
                                            lastCognitiveIndex.toDouble()
                                        ), 0
                                ).toInt()


                    if (lastCognitiveIndex <= maxCognitiveRange.toInt() / 2) {
                        mBlChangeCognitive.lookPosition = 0//箭头再左侧
                        mBlChangeCognitive.x =
                            (20 + lastCognitiveIndexWidth + (currentCognitiveIndexWith - lastCognitiveIndexWidth) / 2).toFloat()
                    } else {
                        mBlChangeCognitive.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthGreen = mTvChangeCognitive.width
                            mBlChangeCognitive.x =
                                (20 + lastCognitiveIndexWidth + (currentCognitiveIndexWith - lastCognitiveIndexWidth) / 2).toFloat() - widthGreen - 10
                        }
                    }
                    mBlChangeCognitive.visibility = View.VISIBLE
                }
                if (currCognitiveIndex < lastCognitiveIndex) {
                    //显示红色衰减进度条
                    val params =
                        mViewCognitionProgress4.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = lastCognitiveIndexWidth - currentCognitiveIndexWith
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(currentCognitiveIndexWith, 0, 0, 0)//设置增长的进度条位置
                    mViewCognitionProgress4.layoutParams = params
                    //显示红色气泡减少值
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#ff4d4d")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeCognitive.text = "-" + Math.abs(
                        DoubleUtils.round(
                            DoubleUtils.sub(
                                currCognitiveIndex.toDouble(),
                                lastCognitiveIndex.toDouble()
                            ), 0
                        ).toInt()
                    )


                    if (lastCognitiveIndex <= maxCognitiveRange.toInt() / 2) {
                        mBlChangeCognitive.lookPosition = 0//箭头再左侧
                        mBlChangeCognitive.x =
                            (20 + currentCognitiveIndexWith + (lastCognitiveIndexWidth - currentCognitiveIndexWith) / 2).toFloat()
                    } else {
                        mBlChangeCognitive.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthRed = mTvChangeCognitive.width
                            mBlChangeCognitive.x =
                                (20 + currentCognitiveIndexWith + (lastCognitiveIndexWidth - currentCognitiveIndexWith) / 2).toFloat() - widthRed - 10
                        }
                    }
                    mBlChangeCognitive.visibility = View.VISIBLE
                }
                if (currCognitiveIndex == lastCognitiveIndex) {
                    mBlChangeCognitive.bubbleColor = Color.parseColor("#00afff")
                    mBlChangeCognitive.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeCognitive.text = "暂无变化"

                    mBlChangeCognitive.x = (20 + currentCognitiveIndexWith / 2).toFloat()
                    mBlChangeCognitive.visibility = View.VISIBLE
                }

                var list = ArrayList<String>(cognitiveRangeListSize)
                for (i in 0 until cognitiveRangeListSize) {
                    val scoreScale = cognitiveBean.CognitionInfo?.CognitiveRangeList!![i]
                    list.add("" + scoreScale)
                }
                var listFlag = ArrayList<String>(cognitiveRangeListSize)
                for (i in 0 until cognitiveRangeListSize) {
                    if (i == (cognitiveRangeListSize - 1)) {
                        listFlag.add("")
                    } else {
                        val scale = ((65 + cognitiveRangeListSize - 2) - i).toChar().toString()
                        listFlag.add(scale)
                    }
                }
                mRlScaleCognitive.removeAllViews()
                showScaleX(mRlScaleCognitive, widthA, list, listFlag)
            }, 50)

            //显示预估成绩变化进度及浮标
            mTvEstimateScore.text = DoubleUtils.killlingDouble(
                DoubleUtils.formatDouble(
                    currEstimateScore!!.toDouble(),
                    1
                )
            )
            mTvEstimateScore.typeface =
                Typeface.createFromAsset(
                    requireContext().assets,
                    "fonts/DIN Condensed Bold.ttf"
                )
            var widthB = 0
            Handler().postDelayed({
                widthB = mViewEstimateProgress1.width

                var lastEstimateScoreWidth =
                    (widthB * lastEstimateScore!! / maxScoreRange.toInt()).toInt()
                var currEstimateScoreWidth =
                    (widthB * currEstimateScore!! / maxScoreRange.toInt()).toInt()

                //显示黄色进度条
                val params =
                    mViewEstimateProgress2.layoutParams as RelativeLayout.LayoutParams
                if (currEstimateScore > lastEstimateScore) {
                    val addWidth = currEstimateScoreWidth - lastEstimateScoreWidth
                    if (addWidth in 1..19) {
                        currEstimateScoreWidth += 20
                    }
                    params.width = currEstimateScoreWidth
                } else {
                    val addWidth = lastEstimateScoreWidth - currEstimateScoreWidth
                    if (addWidth in 1..19) {
                        lastEstimateScoreWidth += 20
                    }
                    params.width = lastEstimateScoreWidth
                }
                mViewEstimateProgress2.layoutParams = params

                if (currEstimateScore > lastEstimateScore) {
                    //显示绿色增长进度条
                    val params =
                        mViewEstimateProgress3.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = currEstimateScoreWidth - lastEstimateScoreWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(lastEstimateScoreWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewEstimateProgress3.layoutParams = params
                    //显示绿色气泡增长值
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#22d7bb")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "+" + DoubleUtils
                        .round(
                            DoubleUtils
                                .sub(
                                    currEstimateScore.toDouble(),
                                    lastEstimateScore.toDouble()
                                ), 0
                        ).toInt()


                    if (lastEstimateScore <= maxScoreRange.toInt() / 2) {
                        mBlChangeEstimate.lookPosition = 0//箭头再左侧
                        mBlChangeEstimate.x =
                            (20 + lastEstimateScoreWidth + (currEstimateScoreWidth - lastEstimateScoreWidth) / 2).toFloat()
                    } else {
                        mBlChangeEstimate.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthGreen = mBlChangeEstimate.width
                            mBlChangeEstimate.x =
                                (20 + lastEstimateScoreWidth + (currEstimateScoreWidth - lastEstimateScoreWidth) / 2).toFloat() - widthGreen + 10
                        }
                    }
                    mBlChangeEstimate.visibility = View.VISIBLE
                }
                if (currEstimateScore < lastEstimateScore) {
                    //显示红色衰减进度条
                    val params =
                        mViewEstimateProgress4.layoutParams as RelativeLayout.LayoutParams
                    val addWidth = lastEstimateScoreWidth - currEstimateScoreWidth
                    if (addWidth < 20) {
                        params.width = 20
                    } else {
                        params.width = addWidth
                    }
                    params.setMargins(currEstimateScoreWidth, 0, 0, 0)//设置增长的进度条位置
                    mViewEstimateProgress4.layoutParams = params
                    //显示红色气泡减少值
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#ff4d4d")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "-" +
                            Math.abs(
                                DoubleUtils.round(
                                    DoubleUtils.sub(
                                        currEstimateScore.toDouble(),
                                        lastEstimateScore.toDouble()
                                    ), 0
                                ).toInt()
                            )

                    if (lastEstimateScore <= maxScoreRange.toInt() / 2) {
                        mBlChangeEstimate.lookPosition = 0//箭头再左侧
                        mBlChangeEstimate.x =
                            (20 + currEstimateScoreWidth + (lastEstimateScoreWidth - currEstimateScoreWidth) / 2).toFloat()
                    } else {
                        mBlChangeEstimate.lookPosition = 100//箭头在右侧
                        Handler().post {
                            val widthRed = mBlChangeEstimate.width
                            mBlChangeEstimate.x =
                                (20 + currEstimateScoreWidth + (lastEstimateScoreWidth - currEstimateScoreWidth) / 2).toFloat() - widthRed + 10
                        }
                    }
                    mBlChangeEstimate.visibility = View.VISIBLE
                }
                if (currEstimateScore == lastEstimateScore) {
                    mBlChangeEstimate.bubbleColor = Color.parseColor("#00afff")
                    mBlChangeEstimate.setBubbleBorderColor(Color.parseColor("#ffffff"))
                    mTvChangeEstimate.text = "暂无变化"

                    mBlChangeEstimate.x = (20 + currEstimateScoreWidth / 2).toFloat()
                    mBlChangeEstimate.visibility = View.VISIBLE
                }

                var list = ArrayList<String>(estimateScoreRangeListSize)
                for (i in 0 until estimateScoreRangeListSize) {
                    val scoreScale = cognitiveBean.CognitionInfo?.EstimateScoreRangeList!![i]
                    list.add("" + scoreScale)
                }
                mRlScaleEstimate.removeAllViews()
                showScaleY(mRlScaleEstimate, widthA, list)
            }, 50)

        }
    }

    /*
    * 刷新认知view
    * */
    fun refreshResultCognitiveView(mCognitiveBean: CognitiveBean) {
        cognitiveBean = mCognitiveBean
        showResultCognitiveView(cognitiveBean)
    }

    /*
    * 显示答题卡view
    * */
    private fun showResultAnswerSheetView(cognitiveBean: CognitiveBean, isShowLoading: Boolean) {
        val mRvAnswerSheetParent =
            mBinding.fmResult3.findViewById<RecyclerView>(R.id.RvAnswerSheetParent)
        val mAnswerSheetLoading =
            mBinding.fmResult3.findViewById<GifMotorbikesView>(R.id.AnswerSheetLoading)

        if (isShowLoading) {
            mAnswerSheetLoading.visibility = View.VISIBLE
        } else {
            mAnswerSheetLoading.visibility = View.GONE
        }
        //加载答题卡
        val manager = LinearLayoutManager(requireContext())
        manager.orientation = LinearLayoutManager.VERTICAL
        mRvAnswerSheetParent.layoutManager = manager

        val adapterParent = ResultAnswerSheetParentAdapter(
            requireActivity(), cognitiveBean
        )
        mRvAnswerSheetParent.adapter = adapterParent
        adapterParent.setClickParentListener(object :
            ResultAnswerSheetParentAdapter.OnClickParentListener {
            override fun onClick(
                index_A: Int,
                index_B: Int,
                index_C: Int
            ) {
                EventBus.getDefault().post(ResultChildClickEvent(index_A, index_B, index_C))
            }
        })
        //刷新后显示答题卡按钮
        mAnswerSheetLoading.visibility = View.GONE
    }

    /*
    * 刷新答题卡view
    * */
    fun refreshResultAnswerSheetView(mCognitiveBean: CognitiveBean) {
        cognitiveBean = mCognitiveBean
        showResultAnswerSheetView(cognitiveBean, false)
    }


    /*
    * 显示进度条刻度(认知积分)
    * */
    private fun showScaleX(
        mRlScaleCognitive: RelativeLayout,
        width_A: Int,
        list: ArrayList<String>,
        listFalg: ArrayList<String>
    ) {
        for (i in 0 until list.size) {
            val mTvScale = TextView(requireContext())
            mTvScale.setTextColor(Color.parseColor("#333333"))
            mTvScale.textSize = 10f
            mTvScale.text = listFalg[i]
            mRlScaleCognitive.addView(mTvScale)
            val bus = MethodUtils.getBusiness(list[i].toDouble(), list[list.size - 1].toDouble())
            if (i == 0) {
                setTextFromLeft(mTvScale, (width_A * bus).toInt())
            } else {
                setTextFromLeft(mTvScale, (width_A * bus).toInt() - 10)
            }
        }
    }

    /*
    * 显示进度条刻度（预估成绩）
    * */
    private fun showScaleY(
        mRlScaleCognitive: RelativeLayout,
        width_A: Int,
        list: ArrayList<String>
    ) {
        for (i in 0 until list.size) {
            val mTvScale = TextView(requireContext())
            mTvScale.setTextColor(Color.parseColor("#333333"))
            mTvScale.textSize = 10f
            mTvScale.text = list[i]
            mRlScaleCognitive.addView(mTvScale)
            val bus = MethodUtils.getBusiness(list[i].toDouble(), list[list.size - 1].toDouble())
            if (i == 0) {
                setTextFromLeft(mTvScale, (width_A * bus).toInt())
            } else {
                setTextFromLeft(mTvScale, (width_A * bus).toInt() - 10)
            }
        }
    }

    private fun setTextFromLeft(Tv: TextView, left: Int) {
        Handler().post {
            //获取控件的宽度
            val tvWidth = Tv.width
            //这里我用FrameLayout布局为列，其他布局设置方法一样，只需改变布局名就行
            val params = Tv.layoutParams as RelativeLayout.LayoutParams
            params.setMargins(left - tvWidth / 2 + 20, 0, 0, 0)
            //改变控件的属性
            Tv.layoutParams = params
        }

    }

    fun hideCognitionInfoView() {
        mBinding.fmResult2.visibility = View.GONE
    }

    override fun onDestroy() {
        super.onDestroy()
        scoreSoundUtils!!.stopAllSoundPool()
    }

    override fun onPause() {
        super.onPause()
        scoreSoundUtils!!.stopAllSoundPool()
    }

}